package com.zlf.annotation;

import com.zlf.exception.RequestLimitException;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: bee-projects</p>
 * <p>Title: EduCourseNoteBean.java</p>
 * <p>Description:   </p>
 * <p>Copyright: Copyright (c) 2016 </p>
 * <p>Company: 华炜云商科技有限公司 www.hwtech.cc</p>
 *
 *  注解实现
 *
 * @author Administrator
 * @version 1.0
 * @date 2017/2/28 10:21
 */
@Aspect
@Component
public class RequestLimitContract {


    /**
     *
     * #目前还有问题
     *
     */

//    private static final Logger logger = LoggerFactory.getLogger("RequestLimitLogger");
//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;
    private static final ThreadLocal<Map<String,Integer>> formatter = new ThreadLocal<Map<String,Integer>>(){};

    @Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
    public void requestLimit(final JoinPoint joinPoint, RequestLimit limit) throws RequestLimitException {

        try {
            Object[] args = joinPoint.getArgs();
            HttpServletRequest request = null;
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof HttpServletRequest) {
                    request = (HttpServletRequest) args[i];
                    break;
                }
            }
            if (request == null) {
                throw new RequestLimitException("方法中缺失HttpServletRequest参数");
            }
            String ip = request.getLocalAddr();
            System.out.println("ip====IP");
            Integer count =formatter.get().get(ip);

            String url = request.getRequestURL().toString();
            String key = "req_limit_".concat(url).concat(ip);
//            long count = redisTemplate.opsForValue().increment(key, 1);
            if (count == null) {
//                redisTemplate.expire(key, limit.time(), TimeUnit.MILLISECONDS);
                formatter.get().put(ip,1);
            }
            if (count > limit.count()) {
                System.out.println("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + limit.count() + "]");
                throw new RequestLimitException();
            }
        } catch (RequestLimitException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发生异常: ");
        }
    }
}